package com.jnu.keepaccounts.record;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jnu.keepaccounts.InputActivity;
import com.jnu.keepaccounts.R;
import com.jnu.keepaccounts.SelectPopWindow;
import com.jnu.keepaccounts.data.Data;
import com.jnu.keepaccounts.data.DataTiaoMu;
import com.jnu.keepaccounts.data.XuanKa;
import com.jnu.keepaccounts.utls.KeyBoardUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ShouZhiFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ShouZhiFragment extends Fragment {

    private FragmentInteraction listener;
    public interface FragmentInteraction{
        void process(DataTiaoMu dataTiaoMu);
    }
    public void onAttach(Activity activity){
        super.onAttach(activity);
        if(activity instanceof FragmentInteraction){
            listener = (FragmentInteraction)activity;
        }
    }

    int yusuan = -1;
    private String zhanghu="微信";
    private Button button_zhanghu;
    private ArrayList<XuanKa> xuanKas = new ArrayList<>();
    private XuankaAdapter xuankaAdapter;
    KeyboardView keyboardView;
    EditText editText;
    int flag = -1;
    int pictureId= R.drawable.eat;
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;


    public ShouZhiFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MainFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ShouZhiFragment newInstance(String param1, String param2) {
        ShouZhiFragment fragment = new ShouZhiFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
    ActivityResultLauncher<Intent> launcherSelect = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            if(data == null)return ;
            else {
                zhanghu = data.getStringExtra("selection");
                button_zhanghu.setText(zhanghu);
            }
        }
    });

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        final int[] year = new int[1];
        final int[] month = new int[1];
        final int[] day = new int[1];
        int position = 0;
        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.fragment_shouzhi, container, false);


        TextView textView = view.findViewById(R.id.textview_xiangmu_xuanze);
        editText = view.findViewById(R.id.edittext_shue);
        Button button_riqi = view.findViewById(R.id.button_riqi);
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView_xuanka);
        Button button_baocun = view.findViewById(R.id.button_baocun);
        Button button_shou_or_zhi = view.findViewById(R.id.shou_or_zhi);



        //设置日期
        Calendar calendar = Calendar.getInstance();
        year[0] = calendar.get(Calendar.YEAR);
        month[0] = calendar.get(Calendar.MONTH)+1;
        day[0] = calendar.get(Calendar.DAY_OF_MONTH);
        button_riqi.setText(year[0] +"-"+ month[0] +"-"+ day[0]);

        this.xuanKas = getArguments().getParcelableArrayList("xuanKas");
        int requestcode = getArguments().getInt("requestcode");
        DataTiaoMu dataTiaoMu = (DataTiaoMu) getArguments().getSerializable("tiaomu");
        if(dataTiaoMu!=null ){
//            position = getArguments().getInt("position",0);
            textView.setText(dataTiaoMu.getXiangMu());
            if(dataTiaoMu.getShuE()>0)flag = 1;
            else flag = -1;
            editText.setHint(Math.abs(dataTiaoMu.getShuE())+"");
            year[0]=dataTiaoMu.getYear();
            month[0] = dataTiaoMu.getMonth();
            day[0] = dataTiaoMu.getDay();
            button_riqi.setText(year[0]+"-"+month[0]+"-"+day[0]);
            pictureId = dataTiaoMu.getImage();
            yusuan = dataTiaoMu.getYusuan();
        }


        //显示自定义软键盘
        keyboardView =  view.findViewById(R.id.keyboardview);
        KeyBoardUtils keyBoardUtils = new KeyBoardUtils(keyboardView,editText);
        keyBoardUtils.showKeyboad();


        LinearLayout linearLayout = view.findViewById(R.id.tou);
        linearLayout.setOnClickListener(v -> {
            keyBoardUtils.hideKeyboard();
        });

        editText.setOnClickListener(v -> {
            keyBoardUtils.showKeyboad();
        });
        button_riqi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //通过自定义控件AlertDialog实现
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                @SuppressLint("ResourceType") View view = (LinearLayout) getLayoutInflater().inflate(R.layout.date, null);
                final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
                //设置日期简略显示 否则详细显示 包括:星期\周
                datePicker.setCalendarViewShown(false);
                //设置date布局
                builder.setView(view);
                builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //日期格式
                        year[0] = datePicker.getYear();
                        month[0] = datePicker.getMonth()+1;
                        day[0] = datePicker.getDayOfMonth();
                        button_riqi.setText(year[0] +"-"+ month[0] +"-"+ day[0] );
                        dialog.cancel();
                    }
                });
                builder.setNegativeButton("取 消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                builder.create().show();
            }
        });

        GridLayoutManager layoutManager = new GridLayoutManager(getContext(),5);
        recyclerView.setLayoutManager(layoutManager);
        xuankaAdapter = new XuankaAdapter(xuanKas);
        recyclerView.setAdapter(xuankaAdapter);

        xuankaAdapter.setOnItemClickListener(new InputActivity.XuankaAdapter.OnItemClickListener(){
            @Override
            public void onItemClicked(View view, int position) {
                textView.setText(xuanKas.get(position).getName());
                flag = xuanKas.get(position).getFlag();
                pictureId = xuanKas.get(position).getPictureId();
            }
        });
        button_shou_or_zhi.setText(flag==1?"收入":"支出");
        button_shou_or_zhi.setOnClickListener(v -> {
            flag = -flag;
            button_shou_or_zhi.setText(flag==1?"收入":"支出");
        });
//        int finalPosition = position;
//        button_baocun.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                DataTiaoMu dataTiaoMu1 = new DataTiaoMu(1,pictureId,(String) textView.getText(),flag*Double.parseDouble(String.valueOf(editText.getText())),zhanghu,year[0],month[0],day[0]);
//                listener.process(dataTiaoMu1);
//            }
//        });
        //设置接口，监听保存

        keyBoardUtils.setOnEnsureListener(new KeyBoardUtils.OnEnsureListener() {
            @Override
            public void onEnsure() {
                double ans=0;
                DataTiaoMu dataTiaoMu1 = null;
                if(editText.getText().toString().equals("")){
                    if(dataTiaoMu!=null){
                        ans = Math.abs(dataTiaoMu.getShuE());
                        dataTiaoMu1 = new DataTiaoMu(1,pictureId,(String) textView.getText(),flag*ans,zhanghu,year[0],month[0],day[0],yusuan,Calendar.getInstance().getTimeInMillis());

                    }
                }
                else {
                    ans = jisuan(editText.getText().toString());
                    dataTiaoMu1 = new DataTiaoMu(1,pictureId,(String) textView.getText(),flag*ans,zhanghu,year[0],month[0],day[0],yusuan,Calendar.getInstance().getTimeInMillis());
                }

                listener.process(dataTiaoMu1);
            }

            @Override
            public void setYuSuan() {
                yusuan = -yusuan;
            }
        });
        button_zhanghu = view.findViewById(R.id.zhanghu);
        button_zhanghu.setOnClickListener(v -> {
            Intent intent = new Intent(getContext(), SelectPopWindow.class);
            launcherSelect.launch(intent);
        });
        return view;
    }


    public double jisuan(String s){
        if(s.equals(""))return 0;
        else{
            for(int i = 0; i < s.length(); i++)
            {
                if(s.charAt(i) == '*' || s.charAt(i) == '/')
                {
                    double num1 = 0, num2 = 0;int len1 = 0, len2 = 0;
                    for(int j = i - 1; j >= 0; j--)
                    {
                        if(s.charAt(j) == '+' || s.charAt(j) == '-')
                        {
                            String s1 = s.substring(j + 1, i);
                            num1 = Double.parseDouble(s1);
                            len1 = s1.length();
                            break;
                        }
                        if(j == 0)
                        {
                            String s1 = s.substring(j, i);
                            num1 = Double.parseDouble(s1);
                            len1 = s1.length();
                            break;
                        }
                    }
                    for(int j = i + 1; j < s.length(); j++)
                    {
                        if(s.charAt(j) == '+' || s.charAt(j) == '-' || s.charAt(j) == '*' || s.charAt(j) == '/' )
                        {
                            String s1 = s.substring(i + 1, j);

                            num2 = Double.parseDouble(s1);
                            len2 = s1.length();
                            break;
                        }
                        if(j == s.length() - 1)
                        {
                            String s1 = s.substring(i + 1, j+1);
                            num2 = Double.parseDouble(s1);
                            len2 = s1.length();
                            break;
                        }
                    }
                    if(s.charAt(i) == '*')
                    {
                        double res = num1 * num2;
                        String s2 = s.substring(i - len1, i +len2 + 1);
                        String s3 = res + "";
                        s = s.replace(s2, s3);
                        i = i - len1 - 1 + s3.length();
                        continue;
                    }
                    if(s.charAt(i) == '/')
                    {
                        double res = num1 / num2;
                        String s2 = s.substring(i - len1, i +len2 + 1);
                        String s3 = res + "";
                        s = s.replace(s2, s3);
                        i = i - len1 - 1 + s3.length();
                        continue;
                    }

                }
            }

            //加减计算
            for(int i = 0; i < s.length(); i++)
            {
                if(s.charAt(i) == '+' || s.charAt(i) == '-')
                {
                    double num1 = 0, num2 = 0;int len1 = 0, len2 = 0;
                    for(int j = i - 1; j >= 0; j--)
                    {
                        if(j == 0)
                        {
                            String s1 = s.substring(j, i);
                            num1 = Double.parseDouble(s1);
                            len1 = s1.length();
                            break;
                        }
                    }
                    for(int j = i + 1; j < s.length(); j++)
                    {
                        if(s.charAt(j) == '+' || s.charAt(j) == '-')
                        {
                            String s1 = s.substring(i + 1, j);
                            num2 = Double.parseDouble(s1);
                            len2 = s1.length();
                            break;
                        }
                        if(j == s.length() - 1)
                        {
                            String s1 = s.substring(i + 1, j+1);
                            num2 = Double.parseDouble(s1);
                            len2 = s1.length();
                            break;
                        }
                    }
                    if(s.charAt(i) == '+')
                    {
                        double res = num1 + num2;
                        String s2 = s.substring(i - len1, i +len2 + 1);
                        String s3 = res + "";
                        s = s.replace(s2, s3);
                        i = i - len1 - 1 + s3.length();
                        continue;
                    }
                    if(s.charAt(i) == '-')
                    {
                        double res = num1 - num2;
                        String s2 = s.substring(i - len1, i +len2 + 1);
                        String s3 = res + "";
                        s = s.replace(s2, s3);
                        i = i - len1 - 1 + s3.length();
                        continue;
                    }
                }
            }
            return Double.parseDouble(s);
        }
    }



    public void onDetach(){
        super.onDetach();
        listener = null;
    }
    public static class XuankaAdapter extends RecyclerView.Adapter<XuankaAdapter.ViewHolder>{

        private ArrayList<XuanKa> xuanKas;
        private InputActivity.XuankaAdapter.OnItemClickListener onItemClickListener;
        public interface OnItemClickListener{
            void onItemClicked(View view,int position);
        }
        public void setOnItemClickListener(InputActivity.XuankaAdapter.OnItemClickListener clickListener){
            this.onItemClickListener = clickListener;
        }
        public class ViewHolder extends RecyclerView.ViewHolder{
            ImageView xuanka;
            TextView text;

            public ViewHolder (View view,final InputActivity.XuankaAdapter.OnItemClickListener onItemClickListener)
            {
                super(view);
                xuanka = (ImageView) view.findViewById(R.id.xuanka_name);
                text = (TextView)  view.findViewById(R.id.text_name);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(onItemClickListener!= null){
                            int position = getAdapterPosition();
                            if(position!= RecyclerView.NO_POSITION){
                                onItemClickListener.onItemClicked(view ,position);
                            }
                        }
                    }
                });
            }

        }
        public XuankaAdapter(ArrayList<XuanKa> xuanKas){
            this.xuanKas = xuanKas;
        }
        @NonNull
        @Override
        public XuankaAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.xuanka_holder,parent,false);
            XuankaAdapter.ViewHolder holder = new XuankaAdapter.ViewHolder(view,onItemClickListener);
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull XuankaAdapter.ViewHolder holder, int position) {
            XuanKa xuanKa = xuanKas.get(position);
            holder.xuanka.setBackgroundResource(xuanKa.getPictureId());
            holder.text.setText(xuanKa.getName());
        }

        @Override
        public int getItemCount() {
            return xuanKas.size();
        }
    }
}